package com.example.baselib.activity

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.security.keystore.UserNotAuthenticatedException
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.room.*
import androidx.sqlite.db.SupportSQLiteDatabase
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.example.baselib.R
import com.example.baselib.constants.MyConstants
import com.example.baselib.databean.Unitinfo
import com.example.baselib.utils.UnitRoomDatabase
import kotlinx.android.synthetic.main.activity_choose_nick.*
import java.util.concurrent.Executors
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T




/**
 * @author sxygsj.
 * @creat time 2020/8/27 9:09.
 * @description [煤矿选择页面]
 * @chang time 2020/8/27 9:09.
 * @chang describe []
 */

class ChooseNickActivity : BaseActivity() {
    lateinit var mDao: MyDao //数据库操作
    lateinit var adapter: ChooseUnitAdapter
    var callback: FinishCallback? = null //选完回掉接口
    val unitLiveData: MutableLiveData<List<Unitinfo>> by lazy { MutableLiveData<List<Unitinfo>>() }
    override fun layoutResId(): Int = R.layout.activity_choose_nick

    override fun initView() {
        setToolbarMsg("选择煤矿")
        setToolbarColor(R.color.colorDBlue, R.color.colorWhite)
        setToolbarMenu(false, 0)
        mDao = UnitRoomDatabase.getDatabase(this).myDao()
        adapter = ChooseUnitAdapter(R.layout.nick_item)
        all_nick_rcy.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        all_nick_rcy.adapter = adapter
//        adapter.bindToRecyclerView(all_nick_rcy)
        search_nick.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {//EditorInfo.IME_ACTION_SEARCH、EditorInfo.IME_ACTION_SEND等分别对应EditText的imeOptions属性
                queryNickName(v.text.toString())
                val imm =
                    v.context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager

                if (imm.isActive) {

                    imm.hideSoftInputFromWindow(v.applicationWindowToken, 0)

                }
            }
            false
        }
        adapter.setOnItemClickListener { adapter, view, position ->
            val unitinfo = adapter.getItem(position) as Unitinfo
            val intent = Intent()
            intent.putExtra("unitname",unitinfo.nickname)
            intent.putExtra("unitcode",unitinfo.unitcode)
            setResult(0, intent)//有返回值的使用这个，没有要返回的值用setResult(0);
            finish()

        }


    }

    override fun onBackPressed() {
        backOnClick()
    }

    override fun backOnClick() {
        setResult(1)
        super.backOnClick()
    }
    override fun initData() {
        queryAll()
        getUnitNick().observe(this, Observer {
            adapter.setNewData(it)
        })


    }


    /**
     *用一个LiveData 做中间返回监听
     */
    fun queryAll() {
        mDao.queryAll().observe(this, Observer {
            unitLiveData.value = it
        })

    }

    fun queryNickName(name: String) {
        mDao.query(name).observe(this, Observer {
            unitLiveData.value = it
        })
    }

    fun getUnitNick(): LiveData<List<Unitinfo>> {
        return unitLiveData
    }

    fun setCallBack(callback:FinishCallback){
        this.callback=callback

    }


}
interface  FinishCallback{
    fun finish(unitinfo: Unitinfo)
}


@Dao
interface MyDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(unitList: List<Unitinfo>): List<Long>

    @Query("SELECT * FROM Unit_table")
    fun queryAll(): LiveData<List<Unitinfo>>

    @Query("SELECT * FROM Unit_table Where nickname  LIKE '%' || :nickname|| '%'")
    fun query(nickname: String): LiveData<List<Unitinfo>>
}

class ChooseUnitAdapter(layoutResId: Int) :
    BaseQuickAdapter<Unitinfo, BaseViewHolder>(layoutResId) {

    override fun convert(helper: BaseViewHolder, item: Unitinfo?) {
        helper.setText(R.id.nick_name, item?.unitname)

    }
}

